import cookie from '@/utils/cookie.js'

import store from '@/store'
import {
	getLogin,
	postBindList,
	postBalance,
	postSyncUserAndArtist
} from '@/api/user.js'

import {
	getServiceUrlApi, // 获取客服链接
} from '@/api/artist.js'


const getUrlCode = (name) => {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
		''
	])[1].replace(/\+/g, '%20')) || null
}
const state = {
	isWeChat: false,
	weChatCode: '',
	userInfo: {},
	walletInfo: {},
	invitationCodeInfo: '',
	locationInfo: {
		userLat: '',
		userLng: '',
		cityCode: ''
	},
	accountTypeList: [],
	tabCurrent :  0, // tabBar的index
	
	isShow: false, // 是否离开了应用
	hrefUrl: '', // 客服链接
	
	
}
const mutations = {

	
	
	
	/**
	 * 修改客服链接
	 */
	setHrefUrl(state,value){
		state.hrefUrl = value
	},
	
	/**
	 * 是否离开应用
	 */
	setIsShow(state,value){
		state.isShow = value
	},
	
	/**
	 * 修改tabBar的index
	 */
	setTabCurrent(state,value){
		state.tabCurrent = value
	},
	
	setState(state, value) {},
	setIsWeChat(state, value) {
		if (state.isWeChat) return
		const isWeChat = navigator?.userAgent.toLowerCase().indexOf('micromessenger') !== -1 // 是否 在微信浏览器内
		state.isWeChat = isWeChat
	},
	setUserInfo(state, value) {
		state.userInfo = Object.assign(state.userInfo, value)
	},
	setLocationInfo(state, value) {
		state.locationInfo = Object.assign(state.locationInfo, value)
	},
	setAccountTypeList(state, value) {
		state.accountTypeList = value
	},
	setWalletInfo(state, value) {
		state.walletInfo = value
	},
	setInvitationCodeInfo(state, value) {
		state.invitationCodeInfo = value
	},
	handleExit(state, value) {
		if (!value) {
			state.userInfo = {}
			state.weChatCode = ''
			cookie.remove('token')
			return
		}
		state.userInfo = {}
		state.weChatCode = ''
		cookie.remove('token')
	}
}
const actions = {
	/**
	 * 校验跳转
	 */
	getCheckMethod({
		state,
		getters
	}){
		/**
		* 判断是否登录, 0是未登录，1是已登录但是没有电话，2是登录也有电话
		*/
		let loginStatus = 0
		let info = state.userInfo
		
		// 如果有token,那就是登录
		if( Object.keys(info).length > 0 && info.loginToken !== "" && info.loginToken !== null ){
			loginStatus = 1
			
			// 有电话
			if(info.phone !== null && info.phone !== "" && info.phone !== undefined){
				loginStatus = 2
			}
		}
		
		
		// 获取页面栈
		let page = getCurrentPages()
		let route = page[0].route
		
		
		// 如果没登录,跳转登录
		if(loginStatus === 0){
			
			// 如果不是当前页,那就跳转过去
			if(route !== '/pages/myTab/index'){
				uni.switchTab({
					url: '/pages/myTab/index'
				});
			}
			
		}else if(loginStatus === 1){
			// 登陆了没电话,就去绑定电话
			uni.redirectTo({
				url: '/pages/me/perfectMessage/perfectMessage'
			});
		}
	},
	
	
	/**
	 * 获取客服链接
	 */
	getServiceUrl({
		commit
	}){
		getServiceUrlApi().then(res =>{
			if(res.code !== 200){
				uni.showToast({
					title: '客服链接请求失败',
					duration:3000,
					icon: 'none'
				})
				return
			}
			commit('setHrefUrl',res.data)
		})
	},
	
	
	
	getUserInfo({
		state,
		commit,
		getters,
		dispatch,
		rootGetters
	}) {
		postSyncUserAndArtist().then(res => {
			
			if(res.code === 500){
				uni.showToast({
					title: '登陆已过期，请重新登陆',
					duration: 3000,
					icon:'none'
				});
				
				setTimeout(()=>{
					uni.switchTab({
						url: '/pages/myTab/index'
					});
				},3000)
				
				return
			}
			
			// 如果没有电话就跳转绑定
			if(res.data === null || res.data.phone === null || res.data.phone === null){
				uni.navigateTo({
					url: '/pages/me/perfectMessage/perfectMessage'
				});
				return
			}
			commit('setUserInfo', res.data)
		})
	},
	handleLogin({
		state,
		commit,
		getters,
		dispatch,
		rootGetters
	}, {
		data,
		path
	}) {
		// getLogin({
		// 	code
		// }).then((res) => {
		// {
		// 	data
		// }
		commit('setUserInfo', data)
		cookie.set('token', data?.loginToken || '')
		setTimeout(() => {
			dispatch('handleWallet')
		}, 200)
		
		console.log(path, 'kkkkkk');
		// #ifdef H5
			window.location.replace(path)
		// #endif
		// })
	},
	handleWallet({
		state,
		commit,
		getters,
		dispatch,
		rootGetters
	}) {
		postBalance({
			userId: state.userInfo.id,
			type: 0
		}).then(res => {
			commit('setWalletInfo', res.data || {})
		})
		postBindList({
			userId: state.userInfo.id
		}).then(res => {
			commit('setAccountTypeList', res.data || [])
		})
	},

}
const getters = {
	

	
	tabCurrent(state){
		return state.tabCurrent
	},
	
	isWeChat(state) {
		return state.isWeChat
	},
	userInfo(state) {
		return state.userInfo || {}
	},
	isLogin(state) {
		return state.userInfo?.loginToken ? true : false
	},
	loginToken(state) {
		return state.userInfo?.loginToken || ''
	},
	isLocation(state) {
		return Boolean(state.locationInfo.cityCode)
	},
	locationInfo(state) {
		return state.locationInfo
	},
	accountTypeList(state) {
		return state.accountTypeList
	},
	zfbInfo(state) {
		return state.accountTypeList.find(i => i.accountType === 1) || null
	},
	yhkInfo(state) {
		return state.accountTypeList.find(i => i.accountType === 0) || null
	},
	walletInfo(state) {
		return state.walletInfo
	},
	invitationCodeInfo(state) {
		return state.invitationCodeInfo || null

	}
}
export default {
	state,
	mutations,
	actions,
	getters
}